package Soul

import (
	codecs "sanguo/codec/cs"
	"sanguo/node/common/com_type"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	table_GamePlay "sanguo/node/table/excel/table/GamePlay"
	//	table_Soul "sanguo/node/table/excel/table/Soul"
	cs_message "sanguo/protocol/cs/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionSoulResolve struct {
	transaction.TransactionBase
	user    *user.User
	req     *codecs.Message
	resp    *cs_message.SoulResolveToC
	errcode cs_message.EnumType
}

func (this *transactionSoulResolve) GetModuleName() string {
	return "Soul"
}

func (this *transactionSoulResolve) GetReplyMsg() proto.Message {
	return &cs_message.SoulResolveToC{}
}

func (this *transactionSoulResolve) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionSoulResolve) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionSoulResolve) Begin() {

	this.resp = &cs_message.SoulResolveToC{}
	msg := this.req.GetData().(*cs_message.SoulResolveToS)

	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()
	if role == nil || !role.IsRoleModleData() {
		node_game.Infoln(role.GetUserID(), "SoulResolve fail : role is nil")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}
	node_game.Infof("%s %d Call SoulResolve id:%d ", role.GetUserID(), role.GetID(), msg.GetSoulIDs())

	//验证功能开启
	if role.GetLev() < table_GamePlay.Table_.IDMap[com_type.GamePaly_Soul].UnlockLevel {
		node_game.Infoln(role.GetUserID(), role.GetID(), "Soul System is not Unlock")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	boolSoul := func(soulIDs []uint64) bool {
		if len(soulIDs) == 0 {
			return false
		}

		for _, sID := range soulIDs {
			soul := role.GetRoleSoul().GetSoul(sID)
			if soul == nil {
				return false
			}
		}
		return true
	}

	if !boolSoul(msg.GetSoulIDs()) {
		node_game.Infoln(role.GetUserID(), role.GetID(), "SoulResolve fail:Condition is fail")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	//发送背包变化
	role.OnSoulDirty()

	node_game.Infoln(role.GetUserID(), role.GetID(), "SoulResolve OK")
	this.errcode = cs_message.EnumType_OK
	this.user.EndTrans(this)
}

func (this *transactionSoulResolve) End() {
	this.resp.Errcode = cs_message.EnumType(this.errcode).Enum()
	this.user.Reply(this.req.GetSeriNo(), this.resp)
}

func (this *transactionSoulResolve) Timeout() {
	this.resp.Errcode = cs_message.EnumType(cs_message.EnumType_RETRY).Enum()
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.SoulResolveToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionSoulResolve{
			user: user,
			req:  msg,
		}
	})
}
